<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>12 成绩案例</title>
    <style>
      td {
        width: 100px ;
        text-align: center;
      }
      .class{
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="app">

      <table border="1">
        <thead>
          <tr>
            <td>编号</th>
            <td>科目</th>
            <td>成绩</th>
            <td>操作</th>
          </tr>
        </thead>
        <tbody v-if="list.length>0">
          <tr v-for="(item,index) in list" :key="item.id">
            <td>{{index+1}}</td>
            <td> {{item.subject}}</td>
            <td :class="{class:item.score<60}">{{item.score}}</td>
            <td> <a href="#" @click.prevent="del(item.id)">删除</a></td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td  rowspan="4" colspan="4">暂无数据</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="4"><span>总分：{{totalCount}}</span> <span>平均分：{{preCount}}</span></td>
          </tr>
        </tfoot>
      </table>
      <div>
        科目：<input type="text" v-model.trim="subject"> <br>
        成绩：<input type="text" v-model.number="score">
        <button @click="add">添加</button>
      </div>

    </div>

    <script src="../js/vue.js"></script>
    <script>
      var app = new Vue({
        el: "#app",
        data: {
          list: [
            { id: 1, subject: "语文", score: 80 },
            { id: 7, subject: "数学", score: 50 },
            { id: 12, subject: "英语", score: 60 },
          ],
          subject:'',
          score:''
        },
        methods: {
          del(id){
            this.list =this.list.filter(item => item.id !== id);
          },
          add(){
            if(this.subject !="" && this.score >=0 && this.score <=100){
              this.list.unshift({
              id:new Date().getTime(),
              subject:this.subject,
              score:this.score
            });
            this.subject='';
            this.score='';
            }
          }
        },
        computed: {
          totalCount(){
            return this.list.reduce((per,cur)=>(per+cur.score),0);
          },
          preCount(){
            if(this.list.length>0){
              return (this.totalCount/this.list.length).toFixed(2); //保留两位小数
            }else{
              return 0;
            }
          }
        },
      });
    </script>
  </body>
</html>
